import os
import gtk
import gtk.glade
import pexpect
from BuildWizException import BuildWizException

class DlgPassword:
    def __init__( self, wizard):
        self.__wiz = wizard
        self.__password = ""
        self.__glade = self.__wiz.getPreferences().getGUIFile( "passwordwindow")
        if not os.path.isfile( self.__glade):
            raise BuildWizException( "DlgPassword: libglade could not open - [%s]" % self.__glade)
        self.__xml = gtk.glade.XML( self.__glade)
        if self.__xml:
            self.__win = self.__xml.get_widget( "DlgPassword")
            self.__win.connect( "destroy", self.__onCancel)
            self.__handlers = { "on_btnOK_clicked": self.__onOK
                              , "on_btnCancel_clicked": self.__onCancel 
                              , "on_entryPassword_changed": self.__onEntryChanged }
            self.__xml.signal_autoconnect( self.__handlers)
            self.__btnOK = self.__xml.get_widget( "btnOK")
            self.__btnOK.set_sensitive( False)
            self.__btnCancel = self.__xml.get_widget( "btnCancel")
            self.__entry = self.__xml.get_widget( "entryPassword")

    def run( self):
        return self.__win.run()

    def __onCancel( self, btn):
        self.__win.destroy()

    def __try2LogAsRoot( self):
        child = pexpect.spawn( "su -")
        i = child.expect( ["Password:.*", pexpect.EOF])
        if i == 0:        
            child.sendline( self.__password)
            i = child.expect( ["root", pexpect.EOF])
            if i == 0:
                child.sendline( "exit")
                return True
            elif i == 1:
                self.__password = ""
                return False

        return False

    def __onOK( self, btn):
        if self.__try2LogAsRoot():
            self.__win.destroy()
        else:
            dlg = gtk.MessageDialog( None, 0
                                   , gtk.MESSAGE_ERROR, gtk.BUTTONS_OK
                                   , "Incorrect root password!")
            dlg.run()
            dlg.destroy()
            self.__entry.set_text( "")

    def getPassword( self):
        return self.__password

    def __onEntryChanged( self, entry):
        self.__password = entry.get_text()
        if self.__password != "":
            self.__btnOK.set_sensitive( True)
        else:
            self.__btnOK.set_sensitive( False)

